
__all__ = ['FlaskzSettingManager']


class FlaskzSettingManager(object):

    def __init__(self, app=None, cfgs=None):

        self.cfgs = None

        if app is not None:
            self.init_app(app, cfgs)

    def init_app(self, app, cfgs=None):
        if cfgs is None:
            raise ValueError("Stock Setting Config Is None")
        if not isinstance(cfgs, dict):
            raise Exception("cfgs必须是dict类型")

        self.cfgs = cfgs

        if not hasattr(app, 'extensions'):
            app.extensions = {}
        app.extensions['cfgs'] = cfgs

    def __getattr__(self, name):
        return getattr(self.cfgs, name)

    def __getitem__(self, name):
        return self.cfgs[name]

    def __setitem__(self, name, value):
        self.cfgs[name] = value

    def __delitem__(self, name):
        del self.cfgs[name]

    def refresh(self, data):
        # TODO 未考虑原子性refresh
        self.cfgs.update(data)
